package com.demo.jwt.service.impl;

import com.demo.jwt.dao.UserDao;
import com.demo.jwt.entity.User;
import com.demo.jwt.form.UserForm;
import com.demo.jwt.service.IUserService;
import com.demo.jwt.utils.MD5Util;
import com.demo.jwt.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    UserDao userDao;

    @Override
    public String login(UserForm userForm) {
        // 判断用户名密码
        User user = userDao.findByUsername(userForm.getUsername());
        if (user == null) {
            log.error("该用户不存在，username->{}", userForm.getUsername());
            return null;
        }
        if (!MD5Util.pass(userForm.getPassword(), user.getPassword())) {
           log.error("密码错误，username->{}", userForm.getUsername());
           return null;
        }
        // 登陆成功 返回token
        return TokenUtil.getToken(user);
    }

    @Override
    public String register(UserForm userForm) {
        User user = userDao.findByUsername(userForm.getUsername());
        if (user != null) {
            log.error("该用户已经存在，username->{}", userForm.getUsername());
            return null;
        }
        // 进行注册
        User newUser = new User();
        newUser.setUsername(userForm.getUsername());
        newUser.setPassword(MD5Util.getMD5(userForm.getPassword()));
        User save = userDao.save(newUser);
        if (save != null) {
            return TokenUtil.getToken(save);
        }
        return null;
    }


}
